package at.codebase.web.servlets.ajax;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import at.codebase.core.search.SearchItem;
import at.codebase.db.dao.EApiPartnerDao;
import at.codebase.db.entities.EApiPartner;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.api.ApiPartnerCalls;
import at.codebase.web.util.json.JsonDecoder;
import at.codebase.web.util.servlet.SecureServlet;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

public class AjaxSearchResultFetcher extends SecureServlet {

	private static final int DEFAULT_LIMIT = 6;

	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ADMIN);
		secLevels.add(UserLevel.REGISTERED);
		secLevels.add(UserLevel.ANONYMOUS);
	}

	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo,
			UserLevel level, RequestType requestType) {
		try {
			String query = requestInfo.getParameters().getString("query");
			StringBuilder queryBuilder = new StringBuilder();
			queryBuilder.append("query=");
			queryBuilder.append(query);
			queryBuilder.append("&limit=");
			queryBuilder.append(String.valueOf(DEFAULT_LIMIT));
			queryBuilder.append("&offset=0");
			Map<EApiPartner, String> result = ApiPartnerCalls
					.makeApiCalls(EApiPartnerDao.getApiPartnerList(), "/webservices/search",
							queryBuilder.toString(), "GET");
			Template mainTemplate = TemplateEngine.getTemplate("external/external_search_results.html");
			ArrayList<Template> sources = new ArrayList<Template>();
			for (EApiPartner p : result.keySet()) {
				Template sourceTemplate = TemplateEngine.getTemplate("external/external_search_provider_results.html");
				sourceTemplate.setHTML("providerName", "<a href=\""+p.getAppUrl()+"\" target=\"_blank\">"+p.getAppName()+"</a>");
				List<SearchItem> items = JsonDecoder.decodeSearchItems(new String(result.get(p)), DEFAULT_LIMIT);
				ArrayList<Template> resultTemplates = new ArrayList<Template>();
				for (SearchItem item : items) {
					Template singleResultTemplate = TemplateEngine.getTemplate("search/item_external_unit.html");
					singleResultTemplate.setText("itemId", item.getItemId());
					singleResultTemplate.setText("partnerId", p.getPartnerId().toString());
					singleResultTemplate.setText("title", item.getTitle());
					singleResultTemplate.setText("imageUrl", item.getImage());
					singleResultTemplate.setText("price", item.getPrice());
					resultTemplates.add(singleResultTemplate);
				}
				sourceTemplate.setTemplates("singleResults", resultTemplates);
				if(items.size() > 0)
					sources.add(sourceTemplate);
			}
			
			if(sources.size() > 0){
				mainTemplate.setTemplates("externalSearchSources", sources);	
			}else{
				mainTemplate.setHTML("externalSearchSources", "<div style=\"width: 500px;text-align:center;margin-left:auto;margin-right:auto;\">Sorry, no partner search results found.</div>");
			}
			
			mainTemplate.render(requestInfo.getLocale());
			writer().printInsecure(mainTemplate.getResult());
		} catch (ParameterDoesNotExistException e) {
			// TODO Auto-generated catch block
			System.out.println("e: " + e);
		}
	}

}
